<!--  Transition不能有多个根结点, 最外层用一个盒子包裹, 不要写两个盒子-->
<template>
  <div>
    <div class="descriptions-box card" v-if="state == 'ready'">
      <span class="text"> {{ name }} </span>
      <span class="break-word"> 本套试卷一共有 {{ question_list.length }} 道题目，请点击下面的“开始练习”来开始</span>
      <p>
        <el-button type="primary" :icon="CirclePlus" @click="start()"> 现在开始 </el-button>
      </p>
    </div>

    <div v-if="state == 'in_process'">
      <div class="descriptions-box card">
        <el-descriptions title="【请填空】 📚" border></el-descriptions>
        <div v-html="question_user?.description"></div>
      </div>
      <div class="descriptions-box card" v-if="question_state == 'answer'">
        <el-descriptions title="【正确答案】 📚" border></el-descriptions>
        <div v-html="question_answer?.description"></div>
      </div>
    </div>

    <div v-if="state == 'score'">
      <el-descriptions title="【完成】 📚" border></el-descriptions>
      <div v-if="after_day === -1">
        <span class="text"> 你已完成了这一单元的学习，以后要继续加油，时不时再来复习哟！</span>
      </div>
      <div v-else-if="question_wrong_arr.length > 0">
        <span class="text"> 你有 {{ question_wrong_arr.length }} 个错题，请再把它们做一遍。 </span>
        <el-button type="primary" :icon="CirclePlus" @click="start(question_wrong_arr)"> 现在开始 </el-button>
      </div>
      <div v-else-if="after_day === 0">
        <span class="text"> 你已完成了第一遍的学习！！ </span>
        <span class="text"> 请趁热打铁再复习一遍~ </span>
        <p>
          <el-button type="primary" :icon="CirclePlus" @click="start()"> 现在开始 </el-button>
        </p>
      </div>
      <div v-else-if="question_wrong_arr.length == 0">
        <span class="text"> 你已完成了这一遍的学习！！ </span>
        <span class="text">
          请在 <span class="text" style="color: green"> {{ AFTER_DAY_DESC[after_day] }} </span> 之后再来复习一遍。
        </span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="exercise">
import { onBeforeMount, onBeforeUnmount, ref } from "vue";
import { CirclePlus } from "@element-plus/icons-vue";
import { getBankQuestionListApi } from "@/api/modules/bank_question";
import { useRouter } from "vue-router";
import { getBankInfoApi } from "@/api/modules/bank";
import { Question } from "@/api/interface";
import {
  addStudyRecordApi,
  getStudyRecordInfoApi,
  getStudyRecordQuestionListApi,
  updateStudyRecordApi
} from "@/api/modules/study_record";

const router = useRouter();
const name = ref<string>("");
let question_index_arr: number[] = [];
let question_wrong_arr: number[] = [];
let question_list: any[] = [];
let question_user = ref<any>();
let question_answer = ref<any>();
let question_index = -1;
const question_state = ref<string>("reply");
const paths = router.currentRoute.value.path.split("/");
let [exercise_type, id] = paths[paths.length - 1].split("=");
const state = ref<string>("ready");
const AFTER_DAY_DESC = ["今天", "明天", "后天", "2天后", "3天后", "4天后", "5天后", "6天后"];
let after_day = 0;
onBeforeMount(async function () {
  if (exercise_type === "bank_id") {
    let question_data = await getBankQuestionListApi({ bank_ids: [id] });
    question_list = question_data.data;

    let bank_data = await getBankInfoApi({ bank_id: id });
    name.value = bank_data.data.name;
  } else if (exercise_type === "study_record_id") {
    let question_data = await getStudyRecordQuestionListApi({ study_record_id: id });
    question_list = question_data.data as Array<any>;

    let study_record_info = await getStudyRecordInfoApi({ study_record_id: id });
    name.value = study_record_info.data.name;
  }
});

const start = (question_index_arrparam = [...Array(question_list.length).keys()]) => {
  state.value = "in_process";
  question_index = -1;
  question_index_arr = JSON.parse(JSON.stringify(question_index_arrparam));
  question_wrong_arr = [];
  window.addEventListener("keydown", handleKeydown);
  nextQuestion();
};

let reg_str_content = /(?<=<u>).*?(?=<\/u>)/g; // 查找所有位于<u>和</u>之间的字符串
let reg_str_format = /<u>.*?<\/u>/g; // 查找所有位于<u>和</u>之间的字符串

const nextQuestion = function () {
  // new question
  question_state.value = "reply";
  question_index += 1;
  let blank_index = 0;

  if (question_index >= question_index_arr.length) {
    return showScore();
  }
  question_user.value = JSON.parse(JSON.stringify(question_list[question_index_arr[question_index]]));
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  question_user.value.description = question_user.value.description.replaceAll(reg_str_format, function (x: string) {
    let replaceString =
      '<input id="' +
      blank_index +
      '" class="input-with-underline" type="text" onkeydown="this.onkeyup();" onkeyup="this.size=(this.value.length>2?this.value.length*2:2);" size="2" autocomplete="off"> ';
    blank_index += 1;
    return replaceString;
  });
  setTimeout(() => {
    document?.getElementById(String(0))?.focus();
  }, 0);
};
const showAnswer = function () {
  question_state.value = "answer";
  let blank_index = 0;
  let blank_all_right = true;
  question_user.value = JSON.parse(JSON.stringify(question_list[question_index_arr[question_index]]));
  question_user.value.description = question_user.value.description.replaceAll(reg_str_content, function (x: string) {
    let inputEle: any = document.getElementById(String(blank_index++));
    if (inputEle?.value === "") {
      blank_all_right = false;
      return '<span style="color: red"> 未填写 </span>';
    } else if (inputEle?.value.trim().toLowerCase().replace(/[-_ ]/g, "") === x.trim().toLowerCase().replace(/[-_ ]/g, "")) {
      return '<span style="color: green">' + x + "</span>";
    } else {
      blank_all_right = false;
      return '<span style="color: red">' + inputEle?.value + "</span>";
    }
  });
  question_answer.value = JSON.parse(JSON.stringify(question_list[question_index_arr[question_index]]));
  question_answer.value.description = question_answer.value.description.replaceAll(reg_str_format, function (x: string) {
    return '<span style="color: green">' + x + "</span>";
  });
  if (!blank_all_right) {
    question_wrong_arr.push(question_index_arr[question_index]);
  }
};
const showScore = async function () {
  window.removeEventListener("keydown", handleKeydown);
  if (question_wrong_arr.length > 0) {
    state.value = "score";
    return;
  }
  if (exercise_type === "bank_id") {
    let question_ids: any[] = [];
    question_list.forEach(elem => {
      question_ids.push(elem.question_id);
    });
    let result = await addStudyRecordApi({ name: name.value, question_ids: JSON.stringify(question_ids) });
    after_day = result.data.after_day;
    exercise_type = "study_record_id";
    id = result.data.study_record_id;
  } else if (exercise_type === "study_record_id") {
    let result = await updateStudyRecordApi({ study_record_id: id });
    after_day = result.data.after_day;
  }

  state.value = "score";
};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handleKeydown = function (event: any) {
  if (event.keyCode === 13) {
    switch (question_state.value) {
      case "reply":
        showAnswer();
        break;
      case "answer":
        if (question_index >= question_index_arr.length) {
          showScore();
        } else {
          nextQuestion();
        }
        break;
    }
  }
};
onBeforeUnmount(function () {
  window.removeEventListener("keydown", handleKeydown);
});
</script>
<style lang="scss">
@import "index";
</style>
